{{- $text := .Get 1 -}}
{{- $locs := $.Site.Data.sref_locations -}}
{{- $loc_titles := $.Site.Data.sref_titles -}}
{{- $k := .Get 0 }}

{{- $numMatches := 0 -}}
{{- $matchPage := "" -}}
{{- range $.Site.Pages }}
  {{- $pageName := partial "nameFromPagePath" .Path -}}
  {{- if (eq $pageName $k) -}}
    {{- $numMatches = add 1 $numMatches -}}
    {{- $matchPage = . -}}
  {{- end -}}
{{- end -}}

{{- $v := slice -}}
{{- if (not (eq $numMatches 1)) }}
  {{- $v = $k | index $locs -}}
  {{- if (eq $v nil) -}}
    {{- errorf "sref: Reference key not found: %v\n" $k -}}
  {{- end -}}
{{- else -}}
  {{- $pathBase := (index (split $matchPage.Path ".") 0) }}
  {{- $v = (split $pathBase "/") }}
  {{- $v = after 1 $v -}}
{{- end -}}

{{- if not (eq $v nil) -}}
  {{- $dstTag := print "/#" (delimit $v "__") -}}

  {{- $dstPagePath := print "/docs/" (delimit $v "/") -}}
  {{- $dstPageObj := $.Site.GetPage $dstPagePath -}}

  {{- $text = default ($dstPageObj.Param "title") $text -}}
  {{- $text = default (index $loc_titles $k) $text -}}

  <a href="{{ $dstTag }}">{{- $text -}}</a>
{{- else -}}
  {{- $text -}}
{{- end -}}

{{- $unused := 17 -}}
